﻿@using System.Timers
@implements IDisposable

<DemoContainer>
    <ApexChart @ref=chart TItem="TimeSeries"
               Title="Order Net Value"
               XAxisType="XAxisType.Datetime"
               Options=options>

        <ApexPointSeries TItem="TimeSeries"
                         Items="generator.TimeSeries"
                         Name="Gross Value"
                         SeriesType="SeriesType.Line"
                         XValue="@(e => e.Date)"
                         YValue="@(e => e.Value)"
                         OrderBy="e=>e.X" />
    </ApexChart>
</DemoContainer>

@code {
    private ApexChart<TimeSeries> chart;
    private ApexChartOptions<TimeSeries> options;
    private TimeSeriesGenerator generator = new TimeSeriesGenerator(20);
    private bool timerInitialized;
    private Timer timer;
    private DateTimeOffset maxDate;
    private int counter;

    protected override void OnInitialized()
    {


        options = new ApexChartOptions<TimeSeries>();

        options.Xaxis = new XAxis
            {
                Range = generator.Range
            };

        options.Yaxis = new List<YAxis> {
            new YAxis {
                Max = 100,
                Min = 0 }
        };
        options.Stroke = new Stroke { Curve = Curve.Smooth };
        options.Chart = new Chart
            {
                Animations = new Animations
                {
                    Easing = Easing.Linear,
                    DynamicAnimation = new DynamicAnimation
                    {
                        Speed = 950
                    }
                },
                Toolbar = new Toolbar
                {
                    Show = false
                },
                Zoom = new Zoom
                {
                    Enabled = false
                }
            };
    }

    protected override void OnAfterRender(bool firstRender)
    {
        if (firstRender && !timerInitialized)
        {
            timerInitialized = true;
            timer = new Timer(1000);
            timer.Elapsed += async delegate { await UpdateChartSeries(); };
            timer.Enabled = true;
        }
    }

    private async Task UpdateChartSeries()
    {

        if (counter > 100) //Reset the chart
        {
            await chart.UpdateSeriesAsync(true);
            counter = 0;
            maxDate = DateTimeOffset.MinValue;
            return;
        }

        if (maxDate == DateTimeOffset.MinValue)
        {
            maxDate = generator.TimeSeries.Max(e => e.Date);
        }

        maxDate = maxDate.AddDays(1);
        await chart.AppendDataAsync(new List<TimeSeries> { generator.GenerateNewPoint(maxDate) });
        counter++;

    }

    public void Dispose()
    {
        timer?.Stop();
        timer = null;
    }


    }